package com.fh.shop.admin.biz.cate;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fh.shop.admin.common.ServerResponse;
import com.fh.shop.admin.mapper.cate.ICateMapper;
import com.fh.shop.admin.po.cate.Cate;
import com.fh.shop.admin.util.RedisUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service("cateService")
public class ICateServiceImpl implements ICateService {
    @Autowired
    private ICateMapper cateMapper;

    @Override
    public ServerResponse findCateList() {
        String cateListJson = RedisUtil.get("cateList");
        if (StringUtils.isNotEmpty(cateListJson)){
            List<Cate> cateList = JSON.parseArray(cateListJson, Cate.class);
            return ServerResponse.success(cateList);
        }
        List<Cate> cateList = cateMapper.selectList(null);
        cateListJson = JSON.toJSONString(cateList);
        RedisUtil.set("cateList",cateListJson);
        return ServerResponse.success(cateList);
    }

    @Override
    public ServerResponse addCate(Cate cate) {
        cateMapper.insert(cate);
        //手动清除缓存
        RedisUtil.del("cateList");
        return ServerResponse.success();
    }

    @Override
    public ServerResponse deleteCate(String ids) {
        if (StringUtils.isNotEmpty(ids)){
            List<Long> idList = Arrays.stream(ids.split(",")).map(x -> Long.parseLong(x)).collect(Collectors.toList());
            cateMapper.deleteBatchIds(idList);
            RedisUtil.del("cateList");
        }
        return ServerResponse.success();
    }

    @Override
    public ServerResponse findCate(Long id) {
        Cate cate = cateMapper.selectById(id);
        return ServerResponse.success(cate);
    }

    @Override
    public ServerResponse updateCate(Cate cate) {
        cateMapper.updateById(cate);
        RedisUtil.del("cateList");
        return ServerResponse.success();
    }

    @Override
    public ServerResponse findCateByFatherId(Long id) {
        QueryWrapper<Cate> cateQueryWrapper = new QueryWrapper<>();
        cateQueryWrapper.eq("fatherId",id);
        List<Cate> cateList = cateMapper.selectList(cateQueryWrapper);
        return ServerResponse.success(cateList);
    }
}
